package models

import (
	"fmt"
	"ginstudydemo.com/main/dao"
	"github.com/jinzhu/copier"
	"strconv"
	"strings"
)

// GetDictPageList 获取字典分页列表
func GetDictPageList(query DictPageQuery, pageParams PaginationParams) ([]DictPageData, int64, int, int, error) {

	var res []DictPageData
	var total int64

	selectQuery := `d.id,
		d.name,
		d.code,
		d.status,
		d.remark,
		d.create_time,
		d.update_time,
		d.is_deleted,
		(
			SELECT JSON_ARRAYAGG(
		JSON_OBJECT(
			'id', di.id,
			'name', di.name,
			'value', di.value,
			'status', di.status,
			'sort', di.sort,
			'remark', di.remark,
			'create_time', di.create_time,
			'update_time', di.update_time
		)
	)
	FROM sys_dict_item di
	WHERE di.dict_id = d.id
	) AS dict_items`

	//FROM
	//sys_dict d
	//WHERE
	//d.is_deleted = 0 -- 排除已删除的数据
	//ORDER BY
	//d.create_time DESC -- 根据创建时间排序
	//LIMIT
	//10 OFFSET 0; -- 分页：每页10条，从第0条开始

	// 主查询用于获取分页数据
	model := dao.Db.Debug().Table("sys_dict d").
		Select(selectQuery).
		Where("d.is_deleted = 0").
		Order("d.create_time DESC")
	// 如果传入了查询条件，则加入模糊查询
	//if query.Keywords != "" {
	//	model = model.Where("u.username LIKE ? OR u.nickname LIKE ? OR u.mobile LIKE ?", "%"+query.Keywords+"%", "%"+query.Keywords+"%", "%"+query.Keywords+"%")
	//}
	//
	//if query.DeptID != "" {
	//	model = model.Where("concat(',', concat(d.tree_path, ',', d.id), ',') LIKE concat('%,', ?, ',%')", query.DeptID)
	//}
	//
	//if query.Status != "" {
	//	model = model.Where("u.status = ?", query.Status)
	//}
	//
	//if query.StartTime != "" && query.EndTime != "" {
	//	model = model.Where("u.create_time >= ? AND u.create_time <= ?", query.StartTime, query.EndTime)
	//}

	// 获取总记录数
	if err := model.Count(&total).Error; err != nil {
		return nil, 0, 0, 0, err
	}
	fmt.Println("-------")

	fmt.Println(total)
	fmt.Println("-------")
	// 添加分页条件
	offset := (pageParams.PageNum - 1) * pageParams.PageSize
	model = model.Limit(pageParams.PageSize).Offset(offset)

	// 执行查询获取分页数据
	if err := model.Scan(&res).Error; err != nil {
		return nil, 0, 0, 0, err
	}

	return res, total, pageParams.PageNum, pageParams.PageSize, nil

}

// GetDictInfoById 根据 id 获取字典数据
func GetDictInfoById(id string) (*DictPageData, error) {

	var result DictPageData

	selectQuery := `d.id,
		d.name,
		d.code,
		d.status,
		d.remark,
		d.create_time,
		d.update_time,
		d.is_deleted,
		(
			SELECT JSON_ARRAYAGG(
		JSON_OBJECT(
			'id', di.id,
			'name', di.name,
			'value', di.value,
			'status', di.status,
			'sort', di.sort,
			'remark', di.remark,
			'create_time', di.create_time,
			'update_time', di.update_time
		)
	)
	FROM sys_dict_item di
	WHERE di.dict_id = d.id
	) AS dict_items`

	model := dao.Db.Debug().Table("sys_dict d").
		Select(selectQuery).
		Where("d.is_deleted = 0").
		Where("d.id = ?", id).
		Order("d.create_time DESC")

	// 执行查询获取分页数据
	if err := model.Scan(&result).Error; err != nil {
		return nil, err
	}

	return &result, nil

}

func AddDict(bodyData DictPageItemRes) (int64, error) {
	var mainTableData AddDictData

	cpErr := copier.Copy(&mainTableData, &bodyData)
	if cpErr != nil {
		return mainTableData.ID, cpErr
	}

	mainErr := dao.Db.Table("sys_dict").Create(&mainTableData).Error // 通过数据的指针来创建

	if mainErr != nil {
		return 0, mainErr
	}

	var AddDictItemDatas []AddDictItem
	for _, item := range bodyData.DictItems {
		AddDictItemDatas = append(AddDictItemDatas, AddDictItem{
			DictId: mainTableData.ID,
			Name:   item.Name,
			Sort:   item.Sort,
			Status: item.Status,
			Value:  item.Value,
		})
	}

	resErr := dao.Db.Table("sys_dict_item").Create(AddDictItemDatas).Error // pass a slice to insert multiple row
	if resErr != nil {
		return 0, mainErr
	}

	return mainTableData.ID, nil

}

// EditDict 修改字典
func EditDict(bodyData DictPageItemRes, dictId string) (string, error) {
	var mainTableData EditDictData
	// 复制为修改主表数据结构
	cpErr := copier.Copy(&mainTableData, &bodyData)
	if cpErr != nil {
		return dictId, cpErr
	}
	// 修改主表数据
	mainErr := dao.Db.Debug().Table("sys_dict").
		Where("id = ?", dictId).
		Updates(&mainTableData).Error
	if mainErr != nil {
		return "", mainErr
	}

	// 清除子表数据
	delErr := dao.Db.Table("sys_dict_item").Where("dict_id = ?", dictId).Delete(&AddDictItem{}).Error
	if delErr != nil {
		return "", delErr
	}
	//组合子表数据
	intValue, strcErr := strconv.ParseInt(dictId, 10, 64)
	if strcErr != nil {
		fmt.Println("Error:", strcErr)
		return "", strcErr
	}
	var AddDictItemDatas []AddDictItem
	for _, item := range bodyData.DictItems {
		AddDictItemDatas = append(AddDictItemDatas, AddDictItem{
			DictId: intValue,
			Name:   item.Name,
			Sort:   item.Sort,
			Status: item.Status,
			Value:  item.Value,
		})
	}
	// 从新 添加子表数据
	resErr := dao.Db.Table("sys_dict_item").Create(AddDictItemDatas).Error // pass a slice to insert multiple row
	if resErr != nil {
		return "", mainErr
	}

	return dictId, nil

}

// DelDict 批量删除字典（硬删除）
func DelDict(ids string) error {

	var idsArr []IdsArr
	for _, val := range strings.Split(ids, ",") {
		valNew, _ := strconv.ParseInt(val, 10, 64)
		idsArr = append(idsArr, IdsArr{
			ID: valNew,
		})
	}
	mainErr := dao.Db.Debug().Table("sys_dict").Delete(&idsArr).Error

	if mainErr != nil {
		return mainErr
	}

	// 清除子表数据
	// 将字符串 "90,98" 转为 []int64
	idStrings := strings.Split(ids, ",") // 按逗号分隔
	var idsInt []int64
	for _, idStr := range idStrings {
		id, err := strconv.ParseInt(strings.TrimSpace(idStr), 10, 64) // 转为 int64
		if err != nil {
			return fmt.Errorf("invalid ID: %s, error: %v", idStr, err)
		}
		idsInt = append(idsInt, id)
	}

	delErr := dao.Db.Table("sys_dict_item").
		Where("dict_id in(?)", idsInt).
		Delete(&AddDictItem{}).Error
	if delErr != nil {
		return delErr
	}
	return nil

}
